package com.CampusForum.community.controller.interceptor;


import com.CampusForum.community.annotation.LoginRequired;
import com.CampusForum.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
    @Autowired
    private HostHolder hostHolder;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (! (handler instanceof HandlerMethod)) {
            // 不是方法略过
            return true;
        }
        // 获取方法注解
        Method method = ((HandlerMethod) handler).getMethod();
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        if (loginRequired != null && hostHolder.getUser() == null) {
            // 被需要登录的注解注释, 但是没有登录的标记
            // 返回主页
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        return true;
    }
}
